package cn.itsource.hrm.service.impl;

import cn.itsource.hrm.domain.Employee;
import cn.itsource.hrm.domain.Tenant;
import cn.itsource.hrm.dto.TenantEnteringDto;
import cn.itsource.hrm.mapper.EmployeeMapper;
import cn.itsource.hrm.mapper.TenantMapper;
import cn.itsource.hrm.service.ITenantService;
import cn.itsource.hrm.utils.encrypt.MD5;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.netflix.discovery.converters.Auto;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xiao
 * @since 2021-03-31
 */
@Service
public class TenantServiceImpl extends ServiceImpl<TenantMapper, Tenant> implements ITenantService {

    @Autowired
    private  TenantMapper tenantMapper;

    @Autowired
    private EmployeeMapper employeeMapper;


    @Value("${hrm.tenant.mealtime}")
    private int mealTime;


    /**
     * 机构入驻
     * 1. 从tenantDto 中获取(机构，员工，套餐)数据
     * 2. 判断数据的合法性（非空，重复，格式验证） // 一定不要相信前端
     * 3. 保存机构数据
     * 4. 保存员工数据
     * 5. 保存机构和套餐的关系
     * @param tenantEnteringDto
     */
    @Override
    @Transactional
    public void entering (TenantEnteringDto tenantEnteringDto) {
        //* 1. 从tenantDto 中获取机构，员工，套餐 数据
        Tenant tenant = tenantEnteringDto.getTenant();
        Employee employee = tenantEnteringDto.getEmployee();
        Long mealId = tenantEnteringDto.getMealId();
        // 注： 不要直接就保存前端接收到的数据, 自己设置默认值
        //保存机构数据
        Date date = new Date();
        tenant.setRegisterTime(date);
        tenant.setState(Tenant.PENDING_REVIEW);  // 0 魔鬼数字 -- 抽取常量
        tenantMapper.insert(tenant);
        //保存员工数据
        //密码加密
        String salt = MD5.getRandomCode(18);
        String md5 = MD5.getMD5(employee.getPassword() + salt);
        employee.setPassword(md5);
        employee.setSalt(salt);
        employee.setState(Employee.NORMAL);
        employee.setInputTime(date);
        employee.setTenantId(tenant.getId());
        employee.setType(Employee.PLATFORM_ADMIN);
        employeeMapper.insert(employee);
        //* 5. 保存机构和套餐的关系
        Long tenantId = tenant.getId();
        Date expireDate = DateUtils.addDays(date, mealTime);
        Integer state = 0;
        tenantMapper.saveTenantAndMeal(mealId, tenantId,expireDate, state);
    }
}
